package com.lixia.lxframework.framework.aspect;

import com.lixia.lxframework.framework.aspect.annotation.TargetDataSource;
import com.lixia.lxframework.framework.datasource.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据源AOP切面处理
 * 通过切面根据注解动态切换数据源
 *
 * @author Administrator
 * @date 2020/6/9
 */
@Slf4j
@Aspect
@Component
public class DataSourceAspect implements Ordered {
    /**
     * 切点: 所有使用 @TargetDataSource 注解的方法
     */
    @Pointcut("@annotation(com.lixia.lxframework.framework.aspect.annotation.TargetDataSource)")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        TargetDataSource targetDataSource = method.getAnnotation(TargetDataSource.class);
        // 通过判断 TargetDataSource 中的值来判断当前方法应用哪个数据源
        DynamicDataSource.setDataSource(targetDataSource.value().name());
        log.info("当前数据源: " + targetDataSource.value().name());
        log.debug("set datasource is " + targetDataSource.value().name());
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.debug("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
